package com.centling.smartSealForPhone.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.centling.smartSealForPhone.BuildConfig;
import com.centling.smartSealForPhone.R;
import com.centling.smartSealForPhone.bean.DeviceTypeBean;
import com.centling.smartSealForPhone.bean.LoginBean;
import com.centling.smartSealForPhone.constants.GlobalData;
import com.centling.smartSealForPhone.constants.SPConstants;
import com.centling.smartSealForPhone.constants.UrlConstants;
import com.wsdk.service.BluetoothLeService;
import com.centling.smartSealForPhone.utils.BlueToothScanUtil;
import com.centling.smartSealForPhone.utils.ControlUtil;
import com.centling.smartSealForPhone.utils.LogUtil;
import com.centling.smartSealForPhone.utils.OkHttpUtil;
import com.centling.smartSealForPhone.utils.ParseBluetoothData;
import com.centling.smartSealForPhone.utils.SPUtil;
import com.centling.smartSealForPhone.utils.ShowDialog;
import com.centling.smartSealForPhone.utils.ShowToast;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;

public class SealChangeTipsActivity
        extends TitleBarActivity
        implements View.OnClickListener, BlueToothScanUtil.StopSearchListener {
    private static final int OPEN_BLUE_DIALOG = 1000;

    private String macAddress;

    private BlueToothScanUtil blueToothScanUtil;

    private DeviceTypeBean deviceTypeBean;

    private String applyId;

    private BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                mProcessDialog.dismiss();
                if (BuildConfig.DEBUG) {
                    ShowToast.shortTime("Seal Change Connected");
                }
                GlobalData.isConnect = true;
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                byte[] data = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);
                if (ParseBluetoothData.isChangeStamp(data)) {
                    new ControlUtil().stamp();
                } else if (ParseBluetoothData.parseOpenByte(data)==0x00) {
                    Map<String, String> param = new HashMap<>();
                    param.put("replaceSealApplyId", applyId);
                    param.put("optResult", "true");
                    postJsonEnqueue(UrlConstants.SEAL_CHANGE_RESULT, param,
                            new OkHttpUtil.NetCallBack() {
                                @Override
                                public void onSucceed(String json) {
                                    Intent intent1 = new Intent(SealChangeTipsActivity.this,
                                            SealChangeGuideOneActivity.class);
                                    intent1.putExtra("applyId", applyId);
                                    startActivity(intent1);
                                    finish();
                                }

                                @Override
                                public void onFailed(String reason) {
                                    ShowToast.shortTime(reason);
                                }
                            });
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_seal_change_tips);
        setTitleBarText("友情提示");

        applyId = getIntent().getStringExtra("applyId");

        LoginBean loginBean = new Gson().fromJson(
                SPUtil.getString(SPConstants.LOGIN_JSON), LoginBean.class);
        macAddress = loginBean.getEquipRegisterInfo().getBlueToothMac();
        sn = SPUtil.getString(SPConstants.CORE_SN);

        if (TextUtils.isEmpty(macAddress)) {
            ShowToast.shortTime("获取用户绑定设备信息失败");
            finish();
        }

        initView();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        registerReceiver(bluetoothReceiver, intentFilter);

        blueToothScanUtil = new BlueToothScanUtil(mContext);
    }

    public void initView() {
        TextView btnCancel = (TextView) findViewById(R.id.tv_seal_change_tips_cancel);
        TextView btnContinue = (TextView) findViewById(R.id.tv_seal_change_tips_continue);
        TextView btnDrop = (TextView) findViewById(R.id.tv_seal_change_tips_drop);

        btnCancel.setOnClickListener(this);
        btnContinue.setOnClickListener(this);
        btnDrop.setOnClickListener(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!BlueToothScanUtil.isBlueToothOpened()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, OPEN_BLUE_DIALOG);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(bluetoothReceiver);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == OPEN_BLUE_DIALOG && resultCode == Activity.RESULT_CANCELED) {
            finish();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_seal_change_tips_cancel:
                finish();
                break;
            case R.id.tv_seal_change_tips_drop:
                Map<String, String> param = new HashMap<>();
                param.put("replaceSealApplyId", applyId);
                param.put("optResult", "false");
                postJsonEnqueue(UrlConstants.SEAL_CHANGE_RESULT, param,
                        new OkHttpUtil.NetCallBack() {
                            @Override
                            public void onSucceed(String json) {
                                ShowToast.shortTime("放弃换章");
                                finish();
                            }

                            @Override
                            public void onFailed(String reason) {
                                ShowToast.shortTime(reason);
                            }
                        });
                break;
            case R.id.tv_seal_change_tips_continue:
                if (!BlueToothScanUtil.isBlueToothOpened()) {
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, OPEN_BLUE_DIALOG);
                    return;
                }
                if (GlobalData.isConnect) {
                    if ("0".equals(GlobalData.selfCheckStatus)) {
                        LogUtil.d(GlobalData.isConnect + "");
                        sendRequestToCheckIsChange();
                    } else {
                        ShowToast.shortTime("设备异常，请联系管理员! ");
                    }
                } else {
                    ShowDialog.showSelectDialog(mContext, "重新连接蓝牙", "蓝牙未连接，请先连接蓝牙", "",
                            new View.OnClickListener() {

                                @Override
                                public void onClick(View v) {
                                    mProcessDialog.setTitle("正在连接蓝牙").showNormal();
                                    blueToothScanUtil.setMacAddress(macAddress);
                                    blueToothScanUtil.startSearchBlueDevice();
                                    blueToothScanUtil.setStopSearchListener(
                                            SealChangeTipsActivity.this);
                                }
                            });
                }
                break;
            default:
                break;
        }
    }

    private void sendRequestToCheckIsChange() {
        getEnqueue(UrlConstants.GET_DEVICE_STATE + GlobalData.REPLACESEAL,
                new OkHttpUtil.NetCallBack() {
                    @Override
                    public void onSucceed(String json) {
                        deviceTypeBean = new Gson().fromJson(json, DeviceTypeBean.class);
                        if (deviceTypeBean.isAllowed()) {
                            ShowToast.shortTime("可以换章！");
                            new ControlUtil().changeStamp();
                        } else {
                            ShowToast.shortTime(deviceTypeBean.getMessage());
                        }
                    }


                    @Override
                    public void onFailed(String reason) {
                        ShowToast.shortTime(reason);
                    }
                });
    }


    @Override
    public void onStopped(boolean timeout) {
        mProcessDialog.dismiss();
        if(timeout) {
            ShowToast.shortTime("连接设备失败");
        }
    }
}
